import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

/// 自动销毁 [StreamSubscription]
///
/// 在 [onClose] 会自动进行销毁
mixin StreamSubscriptionAutoDisposeMixin on GetxController {
  late final List<StreamSubscription> _autoDisposeSubscriptionList = [];

  /// 加入到列表，在 [onClose] 会自动进行销毁
  void addAutoDisposeStreamSubscription(StreamSubscription subscription) {
    _autoDisposeSubscriptionList.add(subscription);
  }

  @override
  void onClose() {
    if (_autoDisposeSubscriptionList.isNotEmpty) {
      for (final subscription in _autoDisposeSubscriptionList) {
        try {
          subscription.cancel();
        } catch (e) {
          debugPrint(e.toString());
        }
      }
    }
    super.onClose();
  }
}

extension StreamSubscriptionExtension on StreamSubscription {
  void autoDispose(StreamSubscriptionAutoDisposeMixin manager) {
    manager.addAutoDisposeStreamSubscription(this);
  }
}
